package faircat.android.exphone;

import android.os.Bundle;
import android.os.Parcelable;
import android.preference.*;
import android.util.Log;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;

import java.lang.reflect.Method;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;

import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;

public class SettingsActivity extends PreferenceActivity implements OnPreferenceClickListener{
	static final BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter();
	static ListPreference mCurDevice;
	static PreferenceCategory mDeviceList;
	static Preference mDeviceSearch;
//	static Preference sms=null;
	static CheckBoxPreference mBluetoothToggle;
	private Preference mUpdateToggle;
	private Preference mAboutToggle;
	private Preference mCloseToggle;
	private Preference mOpenToggle;
	
	static List<String> mNameList = new ArrayList<String>();
	static List<String> mAddressList = new ArrayList<String>();
    private UpdateManager mUpdateManager;
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.preferences);
        mUpdateManager = new UpdateManager(this);  
		PreferenceManager pm = getPreferenceManager();
		mDeviceList = (PreferenceCategory)pm.findPreference("device_list");
		mCurDevice = (ListPreference)pm.findPreference("current_device");
		mDeviceSearch = (Preference)pm.findPreference("device_search");
		mBluetoothToggle = (CheckBoxPreference)pm.findPreference("bluetooth_toggle");
		mBluetoothToggle.setChecked(mBtAdapter.isEnabled());
		
		mUpdateToggle = (Preference)pm.findPreference("update_toggle");
		mUpdateToggle.setOnPreferenceClickListener(this);
		mAboutToggle = (Preference)pm.findPreference("about_toggle");
		mAboutToggle.setOnPreferenceClickListener(this);
		mCloseToggle = (Preference)pm.findPreference("close_toggle");
		mCloseToggle.setOnPreferenceClickListener(this);
		mOpenToggle = (Preference)pm.findPreference("open_toggle");
		mOpenToggle.setOnPreferenceClickListener(this);
		
		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
		filter.addAction("android.bleutooth.device.action.UUID");
		filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
		registerReceiver(mReceiver, filter);
		
		mCurDevice.setEntries(new String[]{});
		mCurDevice.setEntryValues(new String[]{});
		
		// sms = (pm.findPreference("sms_center"));
	//	sms.setOnPreferenceChangeListener(new OnPreferenceChangeListener(){
	//		public boolean onPreferenceChange(Preference preference, Object newValue){
	//			preference.setSummary((String)newValue);
	//			return true;
		//	}
	//	});
		SharedPreferences settings = pm.getDefaultSharedPreferences(this);
	//	sms.setSummary(settings.getString("sms_center", AT.smsCenterNm));
	//	sms.setEnabled(false);
		String address = settings.getString("current_device", "");
		if( address.length()>0){
			BluetoothDevice device = mBtAdapter.getRemoteDevice(address);
			mCurDevice.setSummary(device.getName()+"\n"+device.getAddress());
		}
		mCurDevice.setOnPreferenceChangeListener(new OnPreferenceChangeListener(){
			public boolean onPreferenceChange(Preference preference, Object newValue){
				mBtAdapter.startDiscovery();
				String currAddress = (String)newValue;
				BluetoothDevice device = mBtAdapter.getRemoteDevice(currAddress);
				preference.setSummary(device.getName()+"\n"+currAddress);
				
				Intent i = new Intent(SettingsActivity.this, ExPhoneService.class);
				startService(i);
				return true;
			}
		});
		
		if( mBtAdapter.isEnabled()){
			mBluetoothToggle.setSummary(getString(R.string.bluetooth_opened));
		}
		else{
			mBluetoothToggle.setSummary(getString(R.string.bluetooth_closed));
		}
		
		mNameList.clear();
		mAddressList.clear();
		Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
        if( pairedDevices.size() > 0 ){
        	for( BluetoothDevice device1 :pairedDevices){
				Preference p = new Preference(this);
				p.setTitle(device1.getName());
				p.setSummary(device1.getAddress());
				mDeviceList.addPreference(p);
				mNameList.add(device1.getName() + "\n" + device1.getAddress());
				mAddressList.add(device1.getAddress());	
        	}
			int size = mNameList.size();
			mCurDevice.setEntries((String[])mNameList.toArray(new String[size]));
			mCurDevice.setEntryValues((String[])mAddressList.toArray(new String[size]));
        }
	}
	
	public void onDestroy(){
		unregisterReceiver(mReceiver);
		super.onDestroy();
	}
	
	public boolean onPreferenceTreeClick(PreferenceScreen screen,
			Preference preference){
		if( preference.hasKey()){
			if( preference.getKey().equals("device_search")){
				if(mBtAdapter.isEnabled() && !mBtAdapter.isDiscovering()){
		    		preference.setSummary(getString(R.string.bluetooth_searching));
		    		mBtAdapter.startDiscovery();
		    		mNameList.clear();
		    		mAddressList.clear();
		    		mDeviceList.removeAll();
		    		Log.i("Settings", "find device");
				}
			}
			else if( preference.getKey().equals("bluetooth_toggle")){
				if( mBtAdapter.isEnabled()){
					mBtAdapter.disable();
					preference.setSummary(getString(R.string.bluetooth_closing));
				}
				else{
					mBtAdapter.enable();
					preference.setSummary(getString(R.string.bluetooth_opening));
				}
			}
		}
		return false;
	}
	final BroadcastReceiver mReceiver = new BroadcastReceiver(){
		public void onReceive(Context context, Intent intent)
		{
			String action = intent.getAction();
			if( BluetoothDevice.ACTION_FOUND.equals(action)){
	    		Log.i("Settings", "found device");
				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				String stateString = "";
				Preference p = new Preference(SettingsActivity.this);				
				if( device.getBondState() == BluetoothDevice.BOND_NONE){
					stateString = "|"+getString(R.string.no_bonded);
					p.setOnPreferenceClickListener(new OnPreferenceClickListener(){
						public boolean onPreferenceClick(Preference preference){	
							String address = preference.getSummary().toString();
							BluetoothDevice dev = mBtAdapter.getRemoteDevice(address);
							try{
								Method createBondMethod = BluetoothDevice.class
										.getMethod("createBond");
								createBondMethod.invoke(dev);
							}
							catch(Exception e){
								e.printStackTrace();
							}
							return true;
						}
					});
				}
				p.setTitle(device.getName()+stateString);
				p.setSummary(device.getAddress());
				
				mDeviceList.addPreference(p);
				if( device.getBondState() == BluetoothDevice.BOND_BONDED ){
					mNameList.add(device.getName() + stateString + "\n" + device.getAddress());
					mAddressList.add(device.getAddress());
				}
			}
			else if( BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
				mDeviceSearch.setSummary(getString(R.string.bluetooth_finished));
				int size = mNameList.size();
				mCurDevice.setEntries((String[])mNameList.toArray(new String[size]));
				mCurDevice.setEntryValues((String[])mAddressList.toArray(new String[size]));
			}
			else if( action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)){
				int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
				Intent i = new Intent(SettingsActivity.this, ExPhoneService.class);
				switch(state){
				case BluetoothAdapter.STATE_ON:
		    		Log.i("Settings", "BluetoothAdapter.STATE_ON");
					mBluetoothToggle.setSummary(getString(R.string.bluetooth_opened));
					startService(i);
					break;
				case BluetoothAdapter.STATE_OFF:
		    		Log.i("Settings", "BluetoothAdapter.STATE_OFF");
					mBluetoothToggle.setSummary(getString(R.string.bluetooth_closed));
					stopService(i);
					break;
				}
			}
			else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){   
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);   
                switch (device.getBondState()) {   
                case BluetoothDevice.BOND_BONDING:   
                	for( int i = 0,n = mDeviceList.getPreferenceCount(); i<n;i++){
                		Preference p = mDeviceList.getPreference(i);
                		if( device.getAddress().equals(p.getSummary()) ){
                			p.setTitle(device.getName()+"|"+getString(R.string.bluetooth_bonding));
                		}
                	}
                    break;   
                case BluetoothDevice.BOND_BONDED:
                	for( int i = 0,n = mDeviceList.getPreferenceCount(); i<n;i++){
                		Preference p = mDeviceList.getPreference(i);
                		if( device.getAddress().equals(p.getSummary()) ){
                			p.setTitle(device.getName());
                		}
                	}   
                	if( mAddressList.indexOf(device.getAddress()) != -1){
                		mNameList.add(device.getName() + "\n" + device.getAddress());
                		mAddressList.add(device.getAddress());
                		
        				int size = mNameList.size();
        				mCurDevice.setEntries((String[])mNameList.toArray(new String[size]));
        				mCurDevice.setEntryValues((String[])mAddressList.toArray(new String[size]));
                	}    				
                    break;   
                case BluetoothDevice.BOND_NONE:   
                	break;
                default:   
                    break;   
                }   
            }   
		}
	};
	public boolean onPreferenceClick(Preference preference) {
		// TODO Auto-generated method stub
		if(preference == mUpdateToggle){
	        mUpdateManager.checkUpdateInfo();  
			return true;
		}else if(preference == mAboutToggle){
	        mUpdateManager.showAboutDialog(); 
			return true;
		}else if(preference == mOpenToggle){
			Intent intent = new Intent(this, ExPhoneService.class);
			startService(intent); 
			return true;
		}else if(preference == mCloseToggle){
			Intent intent = new Intent(this, ExPhoneService.class);
			stopService(intent);
			return true;
		}
		return false;
	}
}
